<template>
  <div>
    <CustomForm
      v-if="searchSchame?.length"
      :schemas="searchSchame"
      :formData="queryParams"
      :showSpan="false"
      :inline="true"
    >
      <template #btns>
        <el-form-item>
          <el-button size="small" type="primary" @click="getInfo" icon="Search">
            搜索
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            size="small"
            type="warning"
            @click="reset"
            icon="RefreshRight"
          >
            重置
          </el-button>
        </el-form-item>
      </template>
    </CustomForm>
    <slot name="tableHeader"></slot>
    <Table :data="tableData" :loading="loading" :selectColumn="false">
      <template v-for="column of tableColumns" :key="column.id">
        <TableColumn
          :label="column.label"
          :prop="column.prop"
          :width="column.width"
          :min-width="
            column?.minComputedWidth
              ? getColumnWidth(tableData, column.prop, column.minComputedWidth)
              : column.minWidth
          "
        >
          <template v-if="column.render" #default="{ row }">
            <component :is="column?.render(row)"></component>
          </template>
        </TableColumn>
      </template>
      <slot name="actions"></slot>
    </Table>
    <div class="flex justify-end">
      <el-pagination
        class="pt-4"
        v-model:current-page="cPage"
        v-model:page-size="cSize"
        :page-sizes="[10, 15, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, toRaw, watch } from 'vue'
import Table from '@/components/table/Table.vue'
import TableColumn from '@/components/table/TableColumn.vue'
import { IFormSchemas, ITableColumns } from '@/type/table'
import useFetch from '@/hooks/useFetch'

import { PageParam } from '@/type'
import { getColumnWidth } from '@/plugins/util'
import CustomForm from '../form/CustomForm.vue'
import { cloneDeep } from 'lodash-es'
const props = withDefaults(
  defineProps<{
    // 列表权限
    listPermission?: string
    // 搜索项
    searchSchame?: IFormSchemas[]
    // 表格项
    tableColumns: ITableColumns[]
    // 列表请求api
    api: (params: PageParam) => Promise<any>
    // 列表请求额外参数
    query?: Record<string, any>
    // 自定义处理请求参数
    dealSearchParams?: (params: Record<string, any>) => Record<string, any>
    // 自定义排序字段
    sortField?: string
    // 默认查询参数
    defaultQuery?: Record<string, any>
  }>(),
  {
    listPermission: '',
    query: () => ({}),
    searchSchame: () => [],
  },
)

const tableData = ref([])
const { loading, execute, onFetchSuccess } = useFetch(props.api)

onFetchSuccess((data) => {
  tableData.value = data?.data
  total.value = data.totalCount
})

const formObj = props.searchSchame.reduce((cur, acc) => {
  cur[acc.prop] = props.defaultQuery ? props.defaultQuery[acc.prop] : undefined
  return cur
}, {})

const copyFormObj = cloneDeep(formObj)

const queryParams = reactive(formObj)

onMounted(() => {
  getInfo()
})

const cPage = ref(1)
const cSize = ref(20)
const total = ref(0)

watch(cPage, () => {
  getInfo()
})
watch(cSize, () => {
  getInfo()
})

async function getInfo() {
  const rawParams = toRaw(queryParams)
  const lastParams = props?.dealSearchParams
    ? props.dealSearchParams(rawParams)
    : rawParams
  const postParams = {
    ...lastParams,
    ...props.query,
  }

  const postData: PageParam<typeof postParams> = {
    currentPage: cPage.value,
    pageSize: cSize.value,
    query: postParams,
    sort: props.sortField
      ? [
          {
            field: props.sortField,
            type: 'desc',
          },
        ]
      : [],
  }
  await execute(postData)
}

function reset() {
  Object.assign(queryParams, copyFormObj)
  cPage.value = 1
  cSize.value = 20
  total.value = 0
  getInfo()
}

defineExpose({
  getInfo,
})
</script>
